package com.ctim.web.util.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.*;

public class OSSMutiUploadFile implements Callable<String>{

    public static final Logger LOGGER = Logger.getLogger(OSSMutiUploadFile.class);

    //外层线程池
    public static ExecutorService uploadMainPool = null;
    static{
        uploadMainPool = Executors.newFixedThreadPool(1, r -> {
            Thread s = Executors.defaultThreadFactory().newThread(r);
            s.setDaemon(true);
            return s;
        });
    }
    private OSSClient client;//ossclient
    private String sourcePath;//上传路径
    private BufferedInputStream sourceStream;//上传流
    private String bucketName;//bucketName
    private String key;//云端存储路径
    /**
     * oss上传 支持断点续传
     * @param sourcePath    源文件路径
     * @param bucketName    bucketName
     * @param key           存储key  -在oss的存储路径
     */
    public OSSMutiUploadFile(String sourcePath, String bucketName, String key) {
        //实例化单文件上次线程池
        this.sourcePath = sourcePath;
        this.bucketName = bucketName;
        this.key = key;
    }

    /**
     * oss上传 支持断点续传
     * @param io    源文件路径
     * @param bucketName    bucketName
     * @param key           存储key  -在oss的存储路径
     */
    public OSSMutiUploadFile(BufferedInputStream io, String bucketName, String key) {
        //实例化单文件上次线程池
        this.sourceStream = io;
        this.bucketName = bucketName;
        this.key = key;
    }

    /**
     * 执行当前线程
     * @return int
     */
    public String uploadFile() throws ExecutionException, InterruptedException {
         //向uploadMainPool中submit当前线程
        Future<String> result = uploadMainPool.submit(this);
        return result.get();
//            client.shutdown();
    }


    /**
     * oss上传
     * @return Integer
     */
    @Override
    public String call(){
        String result;
        client  = OSSClientFactory.getInstance();
        // 准备Bucket
        if (sourceStream != null) {
            result = putObjectByStream(client, bucketName, key);
        } else {
            result = putObjectByFile(client, bucketName, key);
        }
        return result;
    }

    private String putObjectByFile(OSSClient ossClient,String bucketName,String key) {
        File uploadFile = new File(this.sourcePath);
        if (!uploadFile.exists()){
            LOGGER.error("==无法找到文件：" + sourcePath);
        }
        ossClient.putObject(bucketName, key, uploadFile);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return "";
    }

    private String putObjectByStream(OSSClient ossClient,String bucketName,String key) {
        ossClient.putObject(bucketName, key, this.sourceStream);
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return "";
    }

    // 创建Bucket
    private void ensureBucket(OSSClient client, String bucketName){
            // 创建bucket
            client.createBucket(bucketName);
            //设置bucket的访问权限，public-read-write权限
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

    }
}